﻿namespace Website.Controllers
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;

    using Wiki;
    using Wiki.Web;
    using Wiki.Web.Mvc;

    using Website.Models;

    public class PageController : Controller
    {
        [Http(Allow = "GET, HEAD, OPTIONS, POST")]
        public ActionResult ContentNegotiation()
        {
            Uri uri = null;

            string q = this.Request.QueryString["q"];
            if (!q.IsNullOrEmpty())
            {
                uri = this.RouteUri("page/{title}", new RouteValueDictionary(new { title = q }));
            }
            else
            {
                if (this.Request.Accepts("application", "xhtml+xml", false))
                {
                    uri = this.RouteUri("page.xhtml");
                }
                else
                {
                    uri = this.RouteUri("page.html");
                }
            }

            return new SeeOtherActionResult(uri);
        }

        [Http(Allow = "GET, HEAD, OPTIONS, POST", SupportedMediaType = "application/x-www-form-urlencoded")]
        public ActionResult Post()
        {
            ActionResult result = null;

            WikiPage page = WikiPage.Edit(this.Request.Form);
            if (0 == page.Errors.Count)
            {
                result = new SeeOtherActionResult(this.RouteUri("page/{title}", new RouteValueDictionary(new { title = page.Title })));
            }
            //else
            //{
            //    if (this.Request.Accepts("application", "xhtml+xml", false))
            //    {
            //        result = this.View("XhtmlRepresentation");
            //    }
            //    else
            //    {
            //        result = this.View("HtmlRepresentation");
            //    }
            //}

            return result;
        }

        [Http(Allow = "GET, HEAD, OPTIONS", ContentLanguage = "en", ContentLocation = "page", ContentType = "text/html")]
        public ActionResult HtmlRepresentation()
        {
            return this.View("HtmlRepresentation");
        }

        [Http(Allow = "GET, HEAD, OPTIONS", ContentLanguage = "en", ContentLocation = "page", ContentType = "application/xhtml+xml")]
        public ActionResult XhtmlRepresentation()
        {
            return this.View("XhtmlRepresentation");
        }
    }
}